package cur.tool.common.filter;

import com.alibaba.fastjson2.JSONWriter;
import cur.nature.framework.core.log.LOG;
import cur.nature.framework.mvc.http.ResponseObject;
import cur.nature.framework.core.util.JsonUtil;
import cur.tool.common.AppContextUtil;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.http.server.ServletServerHttpResponse;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

import java.util.List;

@RestControllerAdvice
public class CustomResponseBodyAdvice implements ResponseBodyAdvice {

    @Override
    public boolean supports(MethodParameter returnType, Class converterType) {
//        return returnType.hasMethodAnnotation(ResponseBody.class);
        return true;
    }

    @Override
    public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType, Class selectedConverterType, ServerHttpRequest request, ServerHttpResponse response) {
        // 异常请求不作处理
        if (((ServletServerHttpResponse)response).getServletResponse().getStatus() != HttpServletResponse.SC_OK) {
            return body;
        }
        //过滤 ignore请求
        String requestURI = request.getURI().getPath();
        if (AppContextUtil.isIgnoreURL(requestURI)){
            return body;
        }

        //封装返回结果
        String result =  ((body!=null)? JsonUtil.toJSONString(body, JSONWriter.Feature.WriteNonStringValueAsString):null);
        if (result != null && result.length() > 200) { // 截断
            result = result.substring(0, 200);
        }
        LOG.info("返回结果: "+result, !"/component/log/v1/api/list".equals(requestURI)); // 过滤日志查询

        // 返回
        if (selectedContentType.includes(MediaType.APPLICATION_JSON)) {
            return (body instanceof ResponseObject)?body: ResponseObject.success(body);
        }
        return body;
    }
}
